import axios from 'axios'
import store from '@/store'

class HttpRequest {
  constructor (baseUrl) {
    this.baseUrl = baseUrl
  }

  /**
   * axios的参数config设置
   * @returns {{baseUrl: *, headers: {}}}
   */
  httpRequestConfig () {
    const token = store.state.user.token
    const userId = store.state.user.userId
    const config = {
      baseURL: this.baseUrl,
      headers: {
        userId: userId,
        token: token
      }
    }
    return config
  }

  /**
   * axios文件上传的config
   * @returns {{baseUrl: *, headers: {userId: string, token, "Content-Type": string}}}
   */
  uploadRequestConfig () {
    const token = store.state.user.token
    const userId = store.state.user.userId
    const config = {
      baseURL: this.baseUrl,
      headers: {
        userId: userId,
        token: token,
        'Content-Type': 'multipart/form-data'
      }
    }
    return config
  }

  /**
   * 拦截请求
   * @param instance
   */
  interceptors (instance) {
    // 添加请求拦截器
    instance.interceptors.request.use(config => {
      // 在发送请求之前做些什么 添加全局的loading
      return config
    }, error => {
      // 对请求错误做些什么
      return Promise.reject(error)
    })

    // 添加响应拦截器
    instance.interceptors.response.use(response => {
      // 对响应数据做点什么
      const { data } = response
      console.log('interceptors#response:', response)
      return data
    }, error => {
      // 对响应错误做点什么
      return Promise.reject(error)
    })
  }

  /**
   * post请求数据
   * @param options
   * @returns {*}
   */
  httpRequest (options) {
    const instance = axios.create()
    // 数据拼接 相同的数据后面覆盖前面
    options = Object.assign(this.httpRequestConfig(), options)
    // 执行拦截
    this.interceptors(instance)
    return instance(options)
  }
  /**
   * get请求
   * @param options
   * @returns {AxiosPromise<any>}
   */
  getRequest (options) {
    const url = options.url
    const params = options.params
    const instance = axios.create(this.httpRequestConfig())
    this.interceptors(instance)
    return instance.get(url, {params})
  }

  /**
   * 文件上传
   * @param options
   * @returns {*}
   */
  uploadRequest (options) {
    const instance = axios.create()
    // 数据拼接 相同的数据后面覆盖前面
    options = Object.assign(this.uploadRequestConfig(), options)
    this.interceptors(instance)
    return instance(options)
  }
}
export default HttpRequest
